const superagent = require('superagent');
const request = require('superagent-charset')(superagent);
const chalk = require('chalk');
const columnify = require('columnify')

const goldUrl = 'https://mybank.icbc.com.cn/servlet/AsynGetDataServlet?Area_code=0200&trademode=1&tranCode=A00462';

function goldQuery(){
    return new Promise((resolve,reject)=>{
        let rspdArray = [];
        request.post(goldUrl)
        .charset('gbk')
        .end((err,res)=>{
            if(err)reject([])
            let obj = JSON.parse(res.text);
            let arr = obj['market'];
            for(let i=0;i<arr.length;i++){
              let rspd ={
                id:arr[i]['prodcode'],
                name:arr[i]['metalname'],
                dir:arr[i]['upordown'],
                dr:arr[i]['openprice_dr'],
                dv:arr[i]['openprice_dv'],
                buy:arr[i]['buyprice'],
                sell:arr[i]['sellprice'],
                middle:arr[i]['middleprice'],
              };
              rspdArray.push(rspd);
            }
            resolve(rspdArray);
        })
    })
}

function goldColor(gold){
    switch(gold.dir){
        case '0':{
            return chalk.whiteBright(gold.middle);
        }
        case '1':{
            return chalk.redBright(gold.middle)
        }
        case '2':{
            return chalk.greenBright(gold.middle)
        }
    }
}

async function query(){
    let data = await goldQuery();
    let gold =  data[0]
    var columns = columnify([{
        '编号':  chalk.cyan(gold.id),
        '名称': chalk.yellow(gold.name),
        '黄金中间价': goldColor(gold),
    }]);
    console.clear();
    console.log(columns);
}
query();
setInterval(()=>{
    query();
},10000);
